package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppClubActivity;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUser;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUserActivityRegistration;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.AppUserActivityRegistrationParam;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppClubActivityMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserActivityRegistrationMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppUserActivityRegistrationService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserActivityRegistrationCreateValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserActivityRegistrationSearchValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserActivityRegistrationUpdateValidate;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppUserActivityRegistrationDetailVo;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppUserActivityRegistrationListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * 用户活动报名实现类
 * @author LikeAdmin
 */
@Service
public class TAppUserActivityRegistrationServiceImpl implements ITAppUserActivityRegistrationService {
        
    @Resource
    TAppUserActivityRegistrationMapper tAppUserActivityRegistrationMapper;

    @Resource
    TAppClubActivityMapper appClubActivityMapper;

    @Resource
    TAppUserMapper appUserMapper;

    /**
     * 用户活动报名列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<TAppUserActivityRegistrationListedVo>
     */
    @Override
    public PageResult<TAppUserActivityRegistrationListedVo> list(PageValidate pageValidate, TAppUserActivityRegistrationSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<TAppUserActivityRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        tAppUserActivityRegistrationMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:activityId@activity_id:int",
            "=:userId@user_id:int",
            "like:name:str",
            "=:pic:str",
        });

        IPage<TAppUserActivityRegistration> iPage = tAppUserActivityRegistrationMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<TAppUserActivityRegistrationListedVo> list = new LinkedList<>();
        for(TAppUserActivityRegistration item : iPage.getRecords()) {
            TAppUserActivityRegistrationListedVo vo = new TAppUserActivityRegistrationListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime().getTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime().getTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 用户活动报名详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return TAppUserActivityRegistration
     */
    @Override
    public TAppUserActivityRegistrationDetailVo detail(Integer id) {
        TAppUserActivityRegistration model = tAppUserActivityRegistrationMapper.selectOne(
                new QueryWrapper<TAppUserActivityRegistration>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TAppUserActivityRegistrationDetailVo vo = new TAppUserActivityRegistrationDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 用户活动报名新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(TAppUserActivityRegistrationCreateValidate createValidate) {
        TAppUserActivityRegistration model = new TAppUserActivityRegistration();
        model.setActivityId(createValidate.getActivityId());
        model.setUserId(createValidate.getUserId());
        model.setName(createValidate.getName());
        model.setPic(createValidate.getPic());
        model.setCreateTime(new Date());
        model.setUpdateTime(new Date());
        tAppUserActivityRegistrationMapper.insert(model);
    }

    /**
     * 用户活动报名编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(TAppUserActivityRegistrationUpdateValidate updateValidate) {
        TAppUserActivityRegistration model = tAppUserActivityRegistrationMapper.selectOne(
                new QueryWrapper<TAppUserActivityRegistration>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setActivityId(updateValidate.getActivityId());
        model.setUserId(updateValidate.getUserId());
        model.setName(updateValidate.getName());
        model.setPic(updateValidate.getPic());
        model.setUpdateTime(new Date());
        tAppUserActivityRegistrationMapper.updateById(model);
    }

    /**
     * 用户活动报名删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        TAppUserActivityRegistration model = tAppUserActivityRegistrationMapper.selectOne(
                new QueryWrapper<TAppUserActivityRegistration>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        tAppUserActivityRegistrationMapper.delete(new QueryWrapper<TAppUserActivityRegistration>().eq("id", id));
    }

    /**
     * 设置报名提醒/立即报名/取消报名
     * @param param
     * @return
     */
    @Override
    public String updateUserActivityRegistration(AppUserActivityRegistrationParam param) {
        Integer activityId = param.getActivityId();
        TAppClubActivity appClubActivity = appClubActivityMapper.selectById(activityId);
        Integer userId = param.getUserId();
        TAppUser appUser = appUserMapper.selectById(userId);
        Integer type = param.getType();
        QueryWrapper<TAppUserActivityRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_id",activityId).eq("user_id",userId);
        TAppUserActivityRegistration registration = Optional.ofNullable(tAppUserActivityRegistrationMapper.selectOne(wrapper)).orElse(new TAppUserActivityRegistration());
        Integer registrationId = registration.getId();
        //设置报名提醒
        if(type==1){
            if(registrationId==null){
                TAppUserActivityRegistration tAppUserActivityRegistration = new TAppUserActivityRegistration();
                tAppUserActivityRegistration.setActivityId(activityId);
                tAppUserActivityRegistration.setUserId(userId);
                tAppUserActivityRegistration.setName(appUser.getNickname());
                tAppUserActivityRegistration.setPic(appUser.getPersonalPic());
                tAppUserActivityRegistration.setCreateTime(new Date());
                tAppUserActivityRegistration.setUpdateTime(new Date());
                tAppUserActivityRegistration.setStatus(1);
                tAppUserActivityRegistrationMapper.insert(tAppUserActivityRegistration);
                return JsonReturn.success("设置报名提醒成功").toJsonStr();
            }
            return JsonReturn.fail("已设置报名提醒失败",40002).toJsonStr();
        }
        //立即报名
        else if (type ==2) {
            //todo 校验用户是否是会员

            //人数上限
            Integer activityMaxAmount = Optional.ofNullable(appClubActivity.getActivityMaxAmount()).orElse(0);
            //已报名人数
            Long count = tAppUserActivityRegistrationMapper.selectCount(new QueryWrapper<TAppUserActivityRegistration>().eq("activity_id", activityId).eq("status", 2));
            Integer num= Math.toIntExact(Optional.ofNullable(count).orElse(0L));
            if(num>=activityMaxAmount){
                return JsonReturn.fail("报名人数已满",40003).toJsonStr();
            }
            if(registrationId!=null){
                registration.setStatus(2);
                registration.setUpdateTime(new Date());
                tAppUserActivityRegistrationMapper.updateById(registration);
            }else{
                TAppUserActivityRegistration tAppUserActivityRegistration = new TAppUserActivityRegistration();
                tAppUserActivityRegistration.setActivityId(activityId);
                tAppUserActivityRegistration.setUserId(userId);
                tAppUserActivityRegistration.setName(appUser.getNickname());
                tAppUserActivityRegistration.setPic(appUser.getPersonalPic());
                tAppUserActivityRegistration.setCreateTime(new Date());
                tAppUserActivityRegistration.setUpdateTime(new Date());
                tAppUserActivityRegistration.setStatus(2);
                tAppUserActivityRegistrationMapper.insert(tAppUserActivityRegistration);
            }
            return JsonReturn.success("报名成功").toJsonStr();
        }
        //取消报名
        else if (type==3) {
            if(registrationId!=null && registration.getStatus()==2){
                tAppUserActivityRegistrationMapper.deleteById(registration);
                return JsonReturn.success("取消报名成功").toJsonStr();
            }
            return JsonReturn.fail("取消报名失败",40004).toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

}
